package com.shyroke.daydayzhuansvc.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.shyroke.daydayzhuanapi.entity.QSpiderImageEntity;
import com.shyroke.daydayzhuanapi.entity.SpiderImageEntity;
import com.shyroke.daydayzhuandao.respository.SpiderImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

@Service
public class SpiderImageService {
    @Autowired
    private JPAQueryFactory factory;
    @Autowired
    private SpiderImageRepository spiderImageRepository;

    public SpiderImageEntity selectByUrl(String url) {
        QSpiderImageEntity qSpiderImageEntity = QSpiderImageEntity.spiderImageEntity;
        List<SpiderImageEntity> list = factory.selectFrom(qSpiderImageEntity).where(qSpiderImageEntity.url.eq(url)).limit(1).fetch();
        return CollectionUtil.isNotEmpty(list)?list.get(0):null;
    }

    public SpiderImageEntity getSpiderImage() {
        Iterator<SpiderImageEntity> iterator = spiderImageRepository.findAll().iterator();
        List<SpiderImageEntity> list = new ArrayList<>();
        while (iterator.hasNext()){
            SpiderImageEntity entity = iterator.next();
            list.add(entity);
        }
        Random random = new Random();
        int index = random.nextInt(list.size());
        return list.get(index);

    }
}
